package org.mcjug;

import java.util.List;

import oauth.signpost.OAuth;

import org.mcjug.model.StatusData;
import org.mcjug.model.YambaUtils;

import winterwell.jtwitter.OAuthSignpostClient;
import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.Twitter.Status;
import android.app.Application;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.preference.PreferenceManager;
import android.util.Log;

public class YambaApplicationImpl extends Application implements
		OnSharedPreferenceChangeListener, YambaApplicationInterface {
	private static final String TAG = YambaApplicationImpl.class.getSimpleName();
	private Twitter twitter;
	private SharedPreferences prefs;
	private boolean serviceRunning;
	private StatusData statusData;

	/* (non-Javadoc)
	 * @see org.mcjug.YambaApplicationInterface#onCreate()
	 */
	@Override
	public void onCreate() {
		super.onCreate();
		this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
		this.prefs.registerOnSharedPreferenceChangeListener(this);
		this.statusData = new StatusData(getApplicationContext());
		Log.i(TAG, "onCreate done");
	}

	/* (non-Javadoc)
	 * @see org.mcjug.YambaApplicationInterface#onTerminate()
	 */
	@Override
	public void onTerminate() {
		super.onTerminate();
		Log.i(TAG, "onTerminate done");
	}

	/* (non-Javadoc)
	 * @see org.mcjug.YambaApplicationInterface#getTwitter()
	 */
	public synchronized Twitter getTwitter() {
		if (twitter == null) {
			String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
			String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
			if (token == "" || secret == "") {
				return null;
			}
			// you must have a file called secret.xml under /res/values with the
			// key and secret for this to work
			OAuthSignpostClient oauthClient = new OAuthSignpostClient(
					getString(R.string.CONSUMER_KEY),
					getString(R.string.CONSUMER_SECRET), token, secret);

			twitter = new winterwell.jtwitter.Twitter("", oauthClient);
		}

		return twitter;
	}

	/* (non-Javadoc)
	 * @see org.mcjug.YambaApplicationInterface#loginToTwitter()
	 */
	public void loginToTwitter() {
		Intent intent = new Intent();
		intent.setClass(getApplicationContext(), OauthActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}

	/* (non-Javadoc)
	 * @see org.mcjug.YambaApplicationInterface#fetchStatusUpdates()
	 */
	public synchronized int fetchStatusUpdates() {
		Log.d(TAG, "Fetching status updates");
		Twitter currentTwitter = this.getTwitter();
		if (currentTwitter == null) {
			Log.d(TAG, "Twitter connection info not initialized");
			YambaUtils.broadcastNeedTwitterLogin(getApplicationContext());
			return 0;
		}
		try {
			List<Status> statusUpdates = currentTwitter.getFriendsTimeline();
			long latestStatusCreatedTime = this.getStatusData()
					.getLatestStatusCreatedAtTime();
			ContentValues values = new ContentValues();
			int count = 0;
			for (Status status : statusUpdates) {
				values.clear();
				values.put(StatusData.C_ID, status.id.toString());
				values.put(StatusData.C_CREATED_AT, status.getCreatedAt()
						.getTime());
				values.put(StatusData.C_SOURCE, status.source);
				values.put(StatusData.C_TEXT, status.text);
				values.put(StatusData.C_USER, status.user.name);
				Log.d(TAG, "Got update with id " + status.getId() + ". Saving");
				getStatusData().insertOrIgnore(values);
				if (status.getCreatedAt().getTime() > latestStatusCreatedTime) {
					count++;
				}
			}
			Log.d(TAG, count > 0 ? "Got " + count + " status updates"
					: "No new status updates");
			return count;
		} catch (Throwable e) {
			Log.e(TAG, "Failed to fetch status updates", e);
			YambaUtils.broadcastNeedTwitterLogin(getApplicationContext());
			return 0;
		}

	}

	/* (non-Javadoc)
	 * @see org.mcjug.YambaApplicationInterface#onSharedPreferenceChanged(android.content.SharedPreferences, java.lang.String)
	 */
	public synchronized void onSharedPreferenceChanged(SharedPreferences sp,
			String key) {
		if (key.equals(getString(R.string.pref_screen_interval_key))) {
			YambaUtils.rescheduleAlarm(getApplicationContext());
		}
	}

	/* (non-Javadoc)
	 * @see org.mcjug.YambaApplicationInterface#isServiceRunning()
	 */
	public boolean isServiceRunning() {
		return serviceRunning;
	}

	/* (non-Javadoc)
	 * @see org.mcjug.YambaApplicationInterface#setServiceRunning(boolean)
	 */
	public void setServiceRunning(boolean serviceRunning) {
		this.serviceRunning = serviceRunning;
	}

	/* (non-Javadoc)
	 * @see org.mcjug.YambaApplicationInterface#getStatusData()
	 */
	public StatusData getStatusData() {
		return statusData;
	}

	/* (non-Javadoc)
	 * @see org.mcjug.YambaApplicationInterface#getProvider()
	 */
	public String getProvider() {
		return prefs.getString(
				getString(R.string.pref_screen_location_provider_key),
				LOCATION_PROVIDER_NONE);
	}

	/* (non-Javadoc)
	 * @see org.mcjug.YambaApplicationInterface#getInterval()
	 */
	public int getInterval() {
		Log.d(TAG,
				"About to get interval, it is: "
						+ prefs.getString(
								getString(R.string.pref_screen_interval_key),
								String.valueOf(INTERVAL_NEVER)));
		String intervalString = prefs.getString(
				getString(R.string.pref_screen_interval_key),
				String.valueOf(INTERVAL_NEVER));
		return Integer.valueOf(intervalString);
	}
}
